;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.AgentReturn", [])
        .controller("AgentReturnCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", "EventBus", "MaterialService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService, EventBus, MaterialService, $stateParams) {
            // tab标签页展示信息
            $scope.activeFlag = [true, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.detailFlag = [true];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false
            };
            $scope.saveStateEnum = {
                save: 0,
                submit: 1
            };
            // 退货单列表分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            // 销售出库单分页信息
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            // 退货单搜索条件
            $scope.condition = {};
            // 销售出库单搜索条件
            $scope.orderCondition = {};
            $scope.orderObj = {};
            // 退货单列表
            $scope.dataList = [];
            // 销售出库单列表
            $scope.orderDataList = [];
            $scope.detailInfo = {
                sex: 1,
                locked: 0
            };
            // 结算信息
            $scope.settleInfo = {};
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };
            // 新增和编辑的标签
            $scope.tabFlag = {};
            $scope.stepList = {
                curStep: 0
            };
            $scope.checkState = [
                {id: 0, name: "未结算"},
                {id: 1, name: "部分结算"},
                {id: 2, name: "已结算"}
            ];
            $scope.saleType = [
                {id: 1, name: "普通"},
                {id: 2, name: "三包"},
                {id: 3, name: "赠送"}
            ];
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/agentReturn/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/agentReturn/exportAll")
            };
            $scope.tableConfig = {
                fixedWidth: 270,
                scrollWidth: 1630,
                tableCol: [
                    {
                        type: "",
                        name: "退货单号",
                        dataField: "returnNo",
                        width: 180,
                        isShow: true,
                        clickFn: "viewDetail",
                    },
                    {
                        type: "",
                        name: "销售出库单号",
                        dataField: "saleOutNo",
                        width: 180,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "creatorName",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createTimeStr",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "总金额",
                        dataField: "totalAmount",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "销售单类型",
                        dataField: "saleTypeStr",
                        width: 120,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "结算状态",
                        dataField: "checkStateStr",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "inboundStatusStr",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusStr",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditTimeStr",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "returnAdvice",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 230,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };
            $scope.tableMaterialConfig = {
                scrollWidth: 1270,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "price",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: false
                    },
                    {
                        type: "",
                        name: "退货数量",
                        dataField: "returnQuantity",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        isInput: true
                    },
                    {
                        type: "",
                        name: "可退数量",
                        dataField: "remainReturnQty",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "实际入库数量",
                        dataField: "returnInboundQty",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "location",
                        name: "储位",
                        dataField: "locationCode",
                        width: 100,
                        isShow: false,
                        isFixed: false
                    }
                ]
            };
            $scope.outTbConf = {
                scrollWidth: 1560,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialNo",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "单位",
                        dataField: "unit",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "订单总数",
                        dataField: "totalOrderQty",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "已发数量",
                        dataField: "issuedQty",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "本次发货",
                        dataField: "thisShipQty",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        isInput: true
                    },
                    {
                        type: "",
                        name: "单价",
                        dataField: "singlePrice",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "实际库存",
                        dataField: "realStockQty",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "意向占用",
                        dataField: "intentOccupation",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "发货占用",
                        dataField: "shipOccupation",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "安全库存",
                        dataField: "safetyStock",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "库存上线",
                        dataField: "onlineStock",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "储位",
                        dataField: "locationCode",
                        width: 150,
                        isShow: true,
                        input: true,
                        inputType: "func"
                    }
                ]
            };
            $scope.saleOutOrderTbConfig = {
                fixedWidth: 60,
                scrollWidth: 1630,
                tableCol: [
                    {
                        type: "",
                        name: "出库单号",
                        dataField: "salesOutBillNo",
                        width: 180,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "销售单号",
                        dataField: "salesBillNo",
                        width: 180,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowBillNo",
                        width: 180,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "clientName",
                        width: 120,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "generatePerson",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "generateDateStr",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "servicePersonName",
                        width: 120,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatusStr",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outboundDateStr",
                        width: 140,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "发出仓库",
                        dataField: "outArea",
                        width: 130,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "结算状态",
                        dataField: "checkStateShow",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "总价",
                        dataField: "totalPrice",
                        width: 80,
                        isShow: true,
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            // 按钮权限code
            var btnPermissionCode = {
                agentReturnAdd: window.ActionCode.agentReturnAdd,
                agentReturnDelete: window.ActionCode.agentReturnDelete,
                agentReturnPrint: window.ActionCode.agentReturnPrint,
                agentReturnEdit: window.ActionCode.agentReturnEdit,
                agentReturnAudit: window.ActionCode.agentReturnAudit,
                agentReturnInbound: window.ActionCode.agentReturnInbound,
                agentReturnFinish: window.ActionCode.agentReturnFinish,
                agentReturnSettle: window.ActionCode.agentReturnSettle,
                agentReturnExport: window.ActionCode.agentReturnExport
            };
            // 按钮权限
            $scope.btnPermission = {
                agentReturnAdd: true,
                agentReturnDelete: true,
                agentReturnPrint: true,
                agentReturnEdit: true,
                agentReturnAudit: true,
                agentReturnInbound: true,
                agentReturnFinish: true,
                agentReturnSettle: true,
                agentReturnExport: true
            };
            // 初始化按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {left: $scope.tableConfig.fixedWidth + "px"},
                    scrollLeftWidth: {width: $scope.tableConfig.fixedWidth + "px"}
                };
                $scope.salesOrderTbStyle = {scrollLeft: {left: $scope.saleOutOrderTbConfig.fixedWidth + "px"}};
            };

            // 批量删除零件
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.detailInfo.list.length; i < len; i++) {
                    if (!!$scope.detailInfo.list[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                for (var j = $scope.detailInfo.list.length - 1; j >= 0; j--) {
                    if (!!$scope.detailInfo.list[j].isChecked && $scope.detailInfo.list[j].status != 2 && $scope.detailInfo.list[j].status != 3) {
                        $scope.detailInfo.list.splice(j, 1);
                    }
                }
                if ($scope.detailInfo.list.length === 0) {
                    $scope.markInfo.allCheckedMaterial = false;
                }
                $scope.setTotalPrice();
            };

            // 删除单个零件
            $scope.delMaterial = function (index) {
                $scope.detailInfo.list.splice(index, 1);
                $scope.setTotalPrice();
            };

            // 切换标签页
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.markInfo.allCheckedMaterial = false;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            };

            // 初始化数据
            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {};
                $scope.stepList.curStep = 0;
                $scope.orderCondition = {};
                $scope.detailFlag = [true];
                $scope.settleInfo = {};
                $scope.submitted = false;
            }

            // 显示与隐藏高级搜索和表格配置项
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            // 表格列的点击事件
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            // 获取需要导出的订单id
            function geBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            // 点击单个checkbox
            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                geBillIds();
            };

            // 检查是否全选
            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            // 选择所有checkbox
            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                geBillIds();
            };

            // 基本信息的展示与隐藏
            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };

            // 单个打印
            $scope.printSingle = function (item) {
                var param = {
                    printType: "AgentReturnOrder",
                    cusParam: { returnIds: [item.id] }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 批量打印
            $scope.batchPrint = function () {
                const selectedIds = $scope.dataList.filter(d => d.isChecked).map(dm => dm.id);
                if (selectedIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "AgentReturnOrder",
                    cusParam: { returnIds: selectedIds }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 上一步
            $scope.prevStep = function () {
                $scope.stepList.curStep = 0;
            };

            // 选择表格行
            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            // 重置搜索条件
            $scope.reset = function () {
                $scope.condition = {};
            };

            function viewDetail (item) {
                getReturnDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(2);
                    }
                })
            }

            // 获取退货单详情
            function getReturnDetail (item) {
                var url = '/agentReturnDetail/item';
                return ybHttp.Get('device', url, {returnIds: [item.id]}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    if (!res.value || res.value.length <= 0) return false;
                    var detailInfo = res.value[0];
                    detailInfo.inboundStatusStr = $filter("ProgressStatus")(detailInfo.inboundStatus, "inDepot");
                    item.saleTypeStr = $filter("BillTypeStatus")(item.saleType);
                    $scope.detailInfo = Object.assign(angular.copy(item), detailInfo);
                    $scope.detailInfo.list = detailInfo.detailVOList;
                    delete $scope.detailInfo.detailVOList;
                    return true;
                })
            }

            // 列表页新增
            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.stepList.curStep = 0;
                getSaleOrderOutList();
                $scope.changeTab(1);
            };

            // 进入编辑页面
            $scope.editData = function (item) {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.stepList.curStep = 1;
                getReturnDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(1);
                    }
                })
            };

            // 新增时搜索销售出库单列表
            $scope.orderSearch = function (curPage) {
                getSaleOrderOutList(curPage);
            };

            // 获取销售出库单列表
            function getSaleOrderOutList (curPage) {
                var reqUrl = "/salesBillOut/availableReturnList";
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.orderPageInfo.pageSize,
                    pageNum: $scope.orderPageInfo.curPage,
                    filters: $scope.orderCondition
                };
                ybHttp.Post('device', reqUrl, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.list, function (item) {
                        item.isChecked = false;
                        item.checkStateShow = $filter("ProgressStatus")(item.checkState, "checkState");
                        item.outboundStatusStr = $filter("ProgressStatus")(item.outboundStatus, "outDepot");
                        item.outboundDateStr = $filter("YbDate")(item.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                        item.generateDateStr = $filter("YbDate")(item.generateDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.orderPageInfo.totalRows = res.value.total;
                    $scope.orderPageInfo.totalPages = res.value.pages;
                    $scope.orderDataList = res.value.list;
                });
            }

            // 选择仓库
            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    $scope.detailInfo.warehouseCode = data.warehouseCode;
                });
            };

            // 清除仓库
            $scope.clearWarehouse = function () {
                $scope.detailInfo.warehouseCode = "";
            };

            // 选择储位
            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.detailInfo.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.locationCode = data.locationCode;
                })
            };

            // 清除储位
            $scope.clearDepot = function (item) {
                item.locationCode = "";
            };

            // 设置头部信息中的订单总价
            $scope.setTotalPrice = function () {
                $scope.checkCount();
                var totalPrice = 0;
                angular.forEach($scope.detailInfo.list, function (item) {
                    if (!item.price) {
                        return false;
                    }
                    // 一条零件的总价，单价乘以本次发货数量
                    var itemTotalPrice = $filter("decimalCover")(ybWidget.Times(parseFloat(item.price), parseFloat(item.returnQuantity)), 2);
                    totalPrice = ybWidget.Plus(totalPrice, itemTotalPrice);
                });
                $scope.detailInfo.totalAmount = $filter("decimalCover")(totalPrice, 2);
            };

            // 新增时点击选择
            $scope.orderSelectSingle = function (item) {
                $scope.stepList.curStep = 1;
                ybHttp.Get('device', '/salesBillOut/getRefundInfo', {id: item.id}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo = {};
                    $scope.detailInfo.saleOutNo = item.salesOutBillNo;
                    $scope.detailInfo.saleOutId = item.id;
                    $scope.detailInfo.clientName = item.clientName;
                    $scope.detailInfo.saleType = item.billType;
                    $scope.detailInfo.saleTypeStr = $filter("BillTypeStatus")(item.billType);
                    $scope.detailInfo.warehouseCode = item.outArea;

                    var materialList = [];
                    angular.forEach(res.value.materialList, function (item) {
                        // 出库数量大于0的才可以退货
                        if (item.outboundQty && item.outboundQty > 0) {
                            materialList.push({
                                isChecked: false,
                                materialNo: item.materialNo,
                                materialDesc: item.materialDes,
                                unit: item.unit,
                                returnQuantity: item.remainReturnQty,
                                remainReturnQty: item.remainReturnQty,
                                price: item.singlePrice,
                                salesOutBillDetailId: item.id
                            });
                        }
                    });
                    $scope.detailInfo.list = materialList;
                    $scope.setTotalPrice();
                });
            };

            // 退货单搜索列表
            $scope.search = function (curpage) {
                $scope.markInfo.allCheckedBill = false;
                $scope.exportParam.sectionParam.ids = [];
                getDataList(curpage);
            };

            // 获取退货单列表
            function getDataList(curPage) {
                var reqUrl = "/agentReturn/list";
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                    filters: angular.copy($scope.condition)
                };
                ybHttp.Post('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        if(item.saleType==2){
                            item.checkState=2;//xbt,审核点击通过按钮如果订单是三包类型，则显示已结算，结算按钮置灰
                        };
                        item.saleTypeStr = $filter("BillTypeStatus")(item.saleType);
                        item.statusStr = $filter("ProgressStatus")(item.status, "returnAudit");
                        item.inboundStatusStr = $filter("ProgressStatus")(item.inboundStatus, "inDepot");
                        item.checkStateStr = $filter("ProgressStatus")(item.checkState, "checkState");
                        item.createTimeStr = $filter("YbDate")(item.createTime, 'yyyy-MM-dd HH:mm:ss');
                        item.auditTimeStr = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                        item.auditTimeStr = $filter("YbDate")(item.auditTime, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            // 修改数量
            $scope.checkCount = function () {
                var bole = true;
                angular.forEach($scope.detailInfo.list, function (item) {
                    if (!item.returnQuantity || item.returnQuantity === 0 || item.returnQuantity > item.remainReturnQty) {
                        bole = false;
                        item.qtyErr = true;
                        item.qtyErrMsg = '退货数量必须大于0且小于可退货数量';
                    } else {
                        item.qtyErr = false;
                        item.qtyErrMsg = '';
                    }
                });
                return bole;
            };

            // 新增页面保存或者提交
            $scope.saveData = function (isValid, status) {
                var bole = $scope.checkCount();
                if (!isValid || !bole) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.detailInfo.list.length === 0) {
                    ybWidget.ShowMessage('必须有零件');
                    return;
                }
                var reqUrl = "/agentReturn/add";
                // 如果有id就是修改退货单
                if ($scope.detailInfo.id) {
                    reqUrl = '/agentReturn/modify';
                }
                var param = angular.copy($scope.detailInfo);
                param.submitFlag = status;
                ybHttp.Post('device', reqUrl, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                });
            };

            // 单个删除
            $scope.deleteSingle = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    delData([id]);
                });
            };

            // 删除退货单
            function delData (ids) {
                var url = '/agentReturn/discardBatch';
                ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                })
            }

            // 进入审核页面
            $scope.goAudit = function (item) {
                getReturnDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(3);
                    }
                });
            };

            // 审核
            $scope.audit = function (flag) {
                if (flag === 0 && !$scope.detailInfo.returnAdvice) {
                    $scope.submitted = true;
                    return;
                }
                var url = "/agentReturn/audit";
                var param = {
                    auditFlag: flag,
                    id: $scope.detailInfo.id,
                    returnAdvice: $scope.detailInfo.returnAdvice
                };
                ybHttp.Post('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.search(1);
                    $scope.changeTab(0);
                })
            };

            // 进入入库页面
            $scope.goInbound = function (item) {
                getReturnDetail(item).then(function (data) {
                    if (data) {
                        $scope.changeTab(4);
                    }
                });
            };

            // 入库
            $scope.inbound = function () {
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.returnNo;
                var errCount = 0;
                angular.forEach($scope.detailInfo.list, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.warehouseCode = $scope.detailInfo.warehouseCode;
                    listRow.areaCode = '';
                    listRow.locationCode = item.locationCode;
                    if (!item.locationCode) {
                        item.locationErr = true;
                        errCount++;
                    }
                    param.detailList.push(listRow);
                });
                if (errCount > 0) return;
                ybHttp.Post('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            // 单个零件结单
            $scope.finishSingle = function (billNo, materialsNo) {
                ybWidget.ShowMessage("确定需要结单吗？", MESG_TYPE.Ask).then(function () {
                    requestUrl('Post', 'finishOrder', {billNo: billNo, materialsNo: materialsNo}).then(function (data) {
                        if (data) {
                            getReturnDetail($scope.detailInfo);
                            $scope.search(1);
                        }
                    })
                });
            };

            /**
             * 整个退货单结单
             * @param id 退货单id
             * @param changeTab  是否切换tab
             */
            $scope.finishOrder = function (billNo, changeTab) {
                ybWidget.ShowMessage("确定需要结单吗？", MESG_TYPE.Ask).then(function () {
                    requestUrl('Post', 'finishOrder', {billNo: billNo}).then(function (data) {
                        if (!data) return;
                        $scope.search(1);
                        if (changeTab) {
                            $scope.changeTab(0);
                        }
                    })
                });
            };

            // 选择经办人
            $scope.selectOperator = function () {
                var param = {
                    name: "经办人",
                    type: "agent",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.settleInfo.operatorId = data.userId;
                    $scope.settleInfo.operatorName = data.name;
                })
            };

            // 去结算页面
            $scope.goSettlement = function (item) {
                getOwedMoney(item.id);
                $scope.settleInfo = {
                    saleType: item.saleType,
                    totalPrice: item.settlementAmount,
                    refundNo: item.returnNo,
                    refundId: item.id,
                    checkType: 0,
                    settleType: 0,
                    owedMoney: 0,
                    refundAmount: item.settlementAmount
                };
                $scope.changeTab(5);
            };

            // 自动算出退款金额
            $scope.changeMoney = function () {
                var total = $scope.settleInfo.totalPrice;                                     // 退款总额
                var lossAmount = getPrice($scope.settleInfo.lossAmount);                            // 折损金额
                var advancePayRefundPrice = getPrice($scope.settleInfo.advancePayRefundPrice);      // 预付款
                var useVehicleRefundQuota = getPrice($scope.settleInfo.useVehicleRefundQuota);      // 车辆额度
                var deductibleAmount = getPrice($scope.settleInfo.deductibleAmount);                // 抵扣欠款金额

                var refundAmount = ybWidget.MultiMinus(total, lossAmount, advancePayRefundPrice, useVehicleRefundQuota, deductibleAmount);
                $scope.settleInfo.refundAmount = refundAmount;
            };

            // 获取价格通用方法
            function getPrice (price) {
                var maxPrice = $scope.settleInfo.totalPrice;
                // 价格不能大于最大值
                var result = parseFloat(price||0);
                return result > maxPrice ? maxPrice : result;
            }

            // 获取欠款金额
            function getOwedMoney (id) {
                var url = UrlObject.owedMoney;
                ybHttp.Get('device', url, {returnId: id}).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    $scope.settleInfo.owedMoney = parseFloat(res.value||0);
                })
            }

            // 提交结算
            $scope.settlement = function (valid) {
                if (!valid || $scope.settleInfo.refundAmount < 0) {
                    $scope.submitted = true;
                    return;
                }
                requestUrl('Post', 'settle', $scope.settleInfo).then(function (data) {
                    if (data) {
                        $scope.search(1);
                        $scope.changeTab(0);
                    }
                });
            };

            var UrlObject = {
                settle: '/refundCheck/add',                  // 结算
                owedMoney: '/agentReturn/getTheAmountOwed',  // 获取欠款金额
                finishOrder: '/agentReturn/manualFinish',    // 结单
                inbound: '/agentReturn/inbound',             // 出库
            };

            /**
             * 请求的公共方法
             * @param type 请求类型
             * @param url  请求路径
             * @param param 请求参数
             * @returns {*|void|Promise<any>|PromiseLike<T | never>|Promise<T | never>}
             */
            function requestUrl (type, url, param) {
                var url = UrlObject[url];
                return ybHttp[type||'Post']('device', url, param).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    return true;
                })
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            (function () {
                // 从销售出库-退货单跳转过来
                if (!!$stateParams.returnId) {
                    viewDetail({id: $stateParams.returnId});
                }
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
